<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter MY_Controller Class
 *
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		ONIPHP CO.,LTD
 * @link		http://www.oniphp.com
 */
class MY_Controller extends CI_Controller {
   	public function __construct()
   	{
        parent::__construct();
        // Your own constructor code
		//Set Cache
		//$this->output->cache(2);		
		//Load Library
		//$this->load->library('solr');
		//Set Time Memcache
		$this->memcache_time = $this->config->item('memcache_time');
		//Set Templates
		$this->folder_templates = "default/";
      	//Set Script Default
   		$this->data['js']    = array('jquery-1.8.3.min.js','jquery.placeholder.min.js','jquery.balloon.min.js','defaultScript.js');
    	//Set Style Default
    	$this->data['css']   = array(''.(!ONIDEV ? 'defaultStyle.min.css':'defaultStyle.css').'','jquery.balloon.css');	
        //Set Script External Default	
        $this->data['external_js']  = '';
        //Set style External Default	
        $this->data['external_css'] = '';	
		//Set Upload Folder
		$this->upload_folder = $this->config->item('path_asset_url').'assets/uploads/';
		//Get Member
		$this->data['member'] = @$this->session->userdata('member');
		//Set Subdomain url
		$this->data['main_url'] = $this->config->item('base_main_url');
		$this->data['award_url'] = $this->config->item('base_award_url');
		$this->data['music_url'] = $this->data['song_url'] = $this->config->item('base_music_url');
		$this->data['video_url'] = $this->config->item('base_video_url');
		$this->data['artist_url'] = $this->config->item('base_artist_url');
		$this->data['news_url'] = $this->config->item('base_news_url');
		$this->data['movie_url'] = $this->config->item('base_movie_url');
		$this->data['search_url'] = $this->config->item('base_search_url');
		$this->data['fashion_url'] = $this->config->item('base_fashion_url');
		$this->data['gallery_url'] = $this->config->item('base_gallery_url');
		$this->data['activity_url'] = $this->config->item('base_activity_url');
		$this->data['search_url'] = $this->config->item('base_search_url');
		$this->data['playlist_url'] = $this->config->item('base_playlist_url');
		$this->data['chord_url'] = $this->config->item('base_chord_url');
		//Set Facebook
		$this->data['fb_api'] = $this->config->item('fb_api');
		$this->data['fb_title'] = "";
		$this->data['fb_description'] = "";
		$this->data['fb_type'] = "website";
		$this->data['fb_image'] = "";
		$this->data['fb_media'] = "";
		//Set SEO
		$this->data['seo_title'] = $this->config->item('seo_title');
		$this->data['seo_description'] = $this->config->item('seo_description');
		$this->data['seo_keyword'] = $this->config->item('seo_keyword');
		//Some Setting
		$this->data['active_wrap_all'] = $this->config->item('active_wrap_all');
		$this->data['active_ads_pushdown'] = $this->config->item('active_ads_pushdown');
		$this->data['active_cover_page'] = $this->config->item('active_cover_page');
		$this->data['active_cover_page_timeout'] = $this->config->item('active_cover_page_timeout');
		$this->data['active_ads_floating'] = $this->config->item('active_ads_floating');
		//Google Analytics
		$this->data['ga_id'] = 1; //www.you2play.com
		$this->data['ga_event'] = ""; //www.you2play.com
		//Hawkeye : The data collection tag
		$this->data['hawkeye_category_name'] = array('Entertainment');
		
		//Calculate Notification
		if ( !$this->data['notification'] = $this->memcache->get('notification')):
			$this->data['notification']['artist_notification'] = $this->db->from('artist')->where("DATE(artist_publish_date) = CURDATE() AND artist_publish_date < NOW()")->count_all_results();
			$this->data['notification']['music_notification'] = $this->db->from('song')->where("DATE(song_publish_date) = CURDATE() AND song_publish_date < NOW()")->count_all_results();
			$this->data['notification']['chords_notification'] = $this->db->from('chords')->where("DATE(chords_publish_date) = CURDATE() AND chords_publish_date < NOW()")->count_all_results();
			$this->data['notification']['video_notification'] = $this->db->from('video')->where("DATE(video_publish_date) = CURDATE() AND video_publish_date < NOW()")->count_all_results();
			$this->data['notification']['movie_notification'] = $this->db->from('movie')->where("DATE(movie_publish_date) = CURDATE() AND movie_publish_date < NOW()")->count_all_results();
			$this->data['notification']['news_notification'] = $this->db->from('news')->where("DATE(news_publish_date) = CURDATE() AND news_publish_date < NOW()")->count_all_results();
			$this->data['notification']['fashion_notification'] = $this->db->from('fashion')->where("DATE(fashion_publish_date) = CURDATE() AND fashion_publish_date < NOW()")->count_all_results();
			$this->data['notification']['gallery_notification'] = $this->db->from('gallery')->where("DATE(gallery_publish_date) = CURDATE() AND gallery_publish_date < NOW()")->count_all_results();
			//Cache Set
			$this->memcache->set('notification', $this->data['notification'], $this->memcache_time);		
		endif;
		
		//Ads Floating
		if($this->data['active_ads_floating'] && !$this->agent->is_mobile() && !$this->agent->is_robot() && $this->router->class != "radio"):
			//Set Script Default
			$this->data['js'][]    = 'jquery.colorbox-min.js';
			//Set Style Default
			$this->data['css'][]   = 'colorbox.css';
		else:
			$this->data['active_ads_floating'] = false;			
		endif;		
		//Cover Page
		//if($this->data['active_cover_page'] && !$this->agent->is_mobile() && !$this->agent->is_robot()):
		if($this->data['active_cover_page'] && !$this->agent->is_robot()):
			if(abs($this->input->cookie('you2play_cover_day') - time()) > $this->data['active_cover_page_timeout']):
		      	//Set Script Default
		   		$this->data['js'][]    = 'jquery.colorbox-min.js';
		    	//Set Style Default
		    	$this->data['css'][]   = 'colorbox.css';
		    	//Time Out
				$mycookie = array(
					'name'  => 'you2play_cover_day',
					'value' => time(),
					'expire'=> ''.$this->data['active_cover_page_timeout'].''
				);
				set_cookie($mycookie);
				$this->data['active_cover_page'] = true;
			else:
				$this->data['active_cover_page'] = false;
			endif;
		else:
			$this->data['active_cover_page'] = false;				
		endif;
		//Cover Page every 1 hours
		//$this->cover_page();		
						
		//Load Library
		//$this->load->library('pagination');
		
		//Google Bot Log
/*		if($this->agent->is_robot('googlebot') && base_url() == "http://movie.you2play.com/"):
			file_put_contents('/home/you2play/engine/static/2013/gbot.txt','***'.urldecode($this->input->server('REQUEST_URI'))."***\nTime:".date('Y-m-d H:i:s')."\n\n",FILE_APPEND);
		endif;*/
   	}
	
	/**************************Cover Page**************************/
	public function cover_page()
	{
		$this->load->view("templates/".$this->folder_templates."templates_cover");
	}
	
	public function devzone_cover_page()
	{
		$this->load->view("templates/".$this->folder_templates."templates_devzone_cover");
	}	
	
	/**************************Ads Floating**************************/
	public function ads_floating()
	{
		$this->load->view("templates/".$this->folder_templates."templates_ads_floating");
	}
	
	/**************************Ads Static**************************/
	public function ajax_ads_static()
	{
		$ads_id = $this->input->post('ads_id');
		$event = $this->input->post('event');
		$date = date('Y-m-d');
		$is_exist = $this->db
		->from('ads_static')
		->where(array('ads_id' => $ads_id,'event' => $event,'date' => $date))
		->count_all_results();
		//UPDATE Ads Statics
		if(!empty($ads_id) && !empty($event)) if(!empty($is_exist)):
			$this->db->set('views', 'views + 1', FALSE);
			$this->db->where(array('ads_id' => $ads_id,'event' => $event,'date' => $date));
			$this->db->update('ads_static');
		else:
			$data = array(
				'ads_id' => $ads_id,
				'event' => $event,
				'views' => 1,
				'date' => $date
			);
			$this->db->insert('ads_static',$data);
		endif;
		//Update Ads
		if($event == "Impression"):
			//UPDATE Ads
			$this->db->set('views', 'views + 1', FALSE);
			$this->db->where(array('ads_id' => $ads_id));
			$this->db->update('ads');		
		elseif($event == "click"):
			//UPDATE Ads
			$this->db->set('click', 'click + 1', FALSE);
			$this->db->where(array('ads_id' => $ads_id));
			$this->db->update('ads');		
		endif;
	}

	/**************************Share Page**************************/
	public function share_page()
	{
		$this->load->view("templates/".$this->folder_templates."templates_share");
	}
	
	/**************************Embed View Stats**************************/	
	public function ajax_view_embed()
	{
		$id = $this->input->post('id');
		$media_type = $this->input->post('media_type');
		$datetime = date('Y-m-d');
		switch($media_type):
			case 'music':
				//UPDATE Song (View)
				$this->db->set('views', 'views + 1', FALSE);
				$this->db->where(array('song_id' => $id));
				$this->db->update('song');
				
				//Keep Stat View
				$is_exist = $this->db->from('song_click_stat')->where(array('song_id' => $id,'update_date' => $datetime))->count_all_results();
				if(!empty($is_exist)):
					$this->db->set('song_click_views', 'song_click_views + 1', FALSE);
					$this->db->where(array('song_id' => $id,'update_date' => $datetime));
					$this->db->update('song_click_stat');
				else:
					$data = array(
						'song_id' => $id,
						'song_click_views' => 1,
						'update_date' => $datetime
					);
					$this->db->insert('song_click_stat',$data);
				endif;			
			break;
			case 'video':
				//UPDATE Video (View)
				$this->db->set('views', 'views + 1', FALSE);
				$this->db->where(array('video_id' => $id));
				$this->db->update('video');
				
				//Keep Stat View
				$datetime = date('Y-m-d');
				$is_exist = $this->db->from('video_click_stat')->where(array('video_id' => $id,'update_date' => $datetime))->count_all_results();
				if(!empty($is_exist)):
					$this->db->set('video_click_views', 'video_click_views + 1', FALSE);
					$this->db->where(array('video_id' => $id,'update_date' => $datetime));
					$this->db->update('video_click_stat');
				else:
					$data = array(
						'video_id' => $id,
						'video_click_views' => 1,
						'update_date' => $datetime
					);
					$this->db->insert('video_click_stat',$data);
				endif;			
			break;
			case 'movie':
				//UPDATE Movie (View)
				$this->db->set('views', 'views + 1', FALSE);
				$this->db->where(array('movie_id' => $id));
				$this->db->update('movie');
				
				//Keep Stat View
				$datetime = date('Y-m-d');
				$is_exist = $this->db->from('movie_click_stat')->where(array('movie_id' => $id,'update_date' => $datetime))->count_all_results();
				if(!empty($is_exist)):
					$this->db->set('movie_click_views', 'movie_click_views + 1', FALSE);
					$this->db->where(array('movie_id' => $id,'update_date' => $datetime));
					$this->db->update('movie_click_stat');
				else:
					$data = array(
						'movie_id' => $id,
						'movie_click_views' => 1,
						'update_date' => $datetime
					);
					$this->db->insert('movie_click_stat',$data);
				endif;				
			break;						
		endswitch;
	}
	
	/**************************Login**************************/
	public function ajax_member_login()
	{
		$member_id = "";
		$fb_id = $this->input->post('fb_id');
		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$rememberme = $this->input->post('rememberme');
		$datetime = date('Y-m-d H:i:s');
		if(empty($password) && !empty($fb_id)): //Facebook Login
			$is_exist = $this->db->from('member')->where(array('fb_id' => $fb_id))->count_all_results();
			if(!empty($is_exist)):
				$is_banned = $this->db->from('member')->where(array('fb_id' => $fb_id,'status' => '3'))->count_all_results();
				if(!empty($is_banned)){
					echo json_encode(array('error' => 1,'msg' => 'คุณถูกแบนจากระบบ โปรดติดต่อเจ้าหน้าที่ You2Play ค่ะ.'));	
					exit;
				}
				$member_id = $this->db->select('member_id')->get_where('member',array('fb_id' => $fb_id),1)->row()->member_id;
				$data = array(
					'last_ip_address' => $this->input->ip_address(),
					'update_date' => $datetime
				);
				$this->db->update('member',$data,array('member_id' => $member_id));
			else: //if not exist then create new one
				//Member
				$data = array(
					'fb_id' => $fb_id,
					'status' => '1',
					'is_newsletter' => '1',
					'last_ip_address' => $this->input->ip_address(),
					'create_date' => $datetime,
					'update_date' => $datetime
				);
				$this->db->insert('member',$data);
				$member_id = $this->db->insert_id();
				//Member Info
				$data = array(
					'member_id' => $member_id,
					'username' => $username
				);
				$this->db->insert('member_info',$data);
			endif;
		endif;
		if(!empty($member_id)):
			$dataMember = $this->db->select('t.member_id,t.fb_id,j.username')
			->join('member_info as j','j.member_id=t.member_id','INNER')
			->get_where('member as t',array('t.member_id' => $member_id),1)
			->row();
			$data = array(
				'error' => 0,
				'member' => array(
					'member_id' => $dataMember->member_id,
					'fb_id' => $dataMember->fb_id,
					'username' => $dataMember->username,
				)
			);
			$this->session->set_userdata($data);
			echo json_encode($data);
		else:		
			echo json_encode(array('error' => 1,'msg' => 'คุณใส่ ชื่อผู้ใช้/รหัสผ่าน ไม่ถูกต้อง.'));		
		endif;
		exit;
	}
	
	public function ajax_member_logout()
	{
		$this->session->unset_userdata('member');
		exit;
	}
	/**************************End Login**************************/
	
	/**************************Playlist**************************/
/*	public function ajax_add_to_playlist()
	{
		$id = $this->input->post('id');
		if(!empty($this->data['member'])): //Member
			$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
			->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
			->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
			->row();
			$this->db->update('playlist_info',array('playlist_song' => $dataPlaylist->playlist_song.':'.$id),array('playlist_id' => $dataPlaylist->playlist_id));
		else:
			if(@get_cookie('you2play_playlist')):
				if(count(explode(':',get_cookie('you2play_playlist'))) >= 20) exit; //Limit 20
				$mycookie = array(
					'name'  => 'you2play_playlist',
					'value' => get_cookie('you2play_playlist').':'.$id,
					'expire'=> '259200'
				);
				set_cookie($mycookie);		
			else:
				$mycookie = array(
					'name'  => 'you2play_playlist',
					'value' => $id,
					'expire'=> '259200'
				);
				set_cookie($mycookie);		
			endif;		
		endif;
	}*/
	
/*	public function ajax_remove_from_playlist()
	{
		$id = $this->input->post('id');
		if(!empty($this->data['member'])): //Member
			$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
			->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
			->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
			->row();
			if(!empty($dataPlaylist->playlist_song)):
				if($id == -1): //Clear All
					$this->db->update('playlist_info',array('playlist_song' => ''),array('playlist_id' => $dataPlaylist->playlist_id));
				else:
					$song_id_arr = explode(':',$dataPlaylist->playlist_song);
					unset($song_id_arr[$id]);
					$this->db->update('playlist_info',array('playlist_song' => implode(':',$song_id_arr)),array('playlist_id' => $dataPlaylist->playlist_id));
				endif;
			endif;
		else:
			if(@get_cookie('you2play_playlist')):
				if($id == -1): //Clear All
					delete_cookie('you2play_playlist');
				else:
					$song_id_arr = explode(':',get_cookie('you2play_playlist'));
					unset($song_id_arr[$id]);
					//$value = preg_replace('/'.$id.'|:'.$id.'/','',get_cookie('you2play_playlist'));
					$mycookie = array(
						'name'  => 'you2play_playlist',
						'value' => implode(':',$song_id_arr),
						'expire'=> '259200'
					);
					set_cookie($mycookie);				
				endif;	
			endif;			
		endif;
	}*/
	
	public function ajax_delete_to_playlist()
	{
		$id = $this->input->post('id');
		if(@get_cookie('you2play_playlist')):
			if($id == -1): //Clear All
				delete_cookie('you2play_playlist');
			else:
				$song_id_arr = explode(':',get_cookie('you2play_playlist'));
				unset($song_id_arr[$id]);
				//$value = preg_replace('/'.$id.'|:'.$id.'/','',get_cookie('you2play_playlist'));
				$mycookie = array(
					'name'  => 'you2play_playlist',
					'value' => implode(':',$song_id_arr),
					'expire'=> '259200'
				);
				set_cookie($mycookie);				
			endif;	
		endif;
	}
	
/*	public function ajax_swap_to_playlist()
	{
		$song = array();
		foreach($_POST as $value):
			$song[] = $value[0];
		endforeach;
		$mycookie = array(
			'name'  => 'you2play_playlist',
			'value' => implode(':',$song),
			'expire'=> '259200'
		);
		set_cookie($mycookie);
	}*/		
	/**************************Playlist**************************/
	
   /**************************Banner Management**************************/	
   public function banner($position)
   {
   		return $this->load->view("banner/banner_".$position, $this->data, true);
   }  
   /**************************End Banner Management**************************/	 
   
   /**************************Module Management**************************/
   /*Initail Setup*/
	public function module($mode='')
	{
		$data = array();
		switch($mode):
			case 'video':
			case 'music':
			case 'artist':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_video_recommend(); //Video Recommend
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->module_dream_ticket(); //Dream Ticket
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_artist_top_chart(); //Artist Top Chart
				$data[] = $this->banner('C'); //Banner C
				//$data[] = "<iframe src='".base_url().'module_video_player'."' width='300' height='170' style='overflow:hidden;border:0;'></iframe>"; //Video Player
				$data[] = $this->module_live_player(); //Live Player	
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin			
			break;
			case 'chords':
			case 'playlist':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player	
			break;			
			case 'movie':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_movie_news(); //Movie News Update
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_movie_song(); //Movie Song Update
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player
				$data[] = $this->module_movie_timeline(); //Movie Timeline		
			break; 
			case 'news':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_calendar(); //News Calendar
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->module_keyword_tag(); //Keyword Tag
			break;
			case 'activity':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_calendar(); //News Calendar
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_activity(); //Activity
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player	
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->module_keyword_tag(); //Keyword Tag
			break;			
			case 'calendar':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player	
				$data[] = $this->module_keyword_tag(); //Keyword Tag
			break;
			case 'gallery':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_gallery_hot(); //Gallery Hot
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player	
			break;			
			case 'fashion':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_artist_top_chart(); //Artist Top Chart				
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player
			break;
			case 'search':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_live_player(); //Live Player	
			break;
			case 'devzone':
				$data[] = $this->banner('A'); //Banner A
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_article(); //Article
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_gallery_new(); //Gallery New
				$data[] = $this->banner('D'); //Banner D
				$data[] = $this->module_calendar(); //Calendar
				$data[] = $this->banner('E'); //Banner E
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->module_activity(); //Activity
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				$data[] = $this->module_keyword_tag(); //Keyword Tag
				$data[] = $this->banner('F'); //Banner F			
			break;
			case 'itzone':
				//$data[] = $this->module_login(); //Login
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart				
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->module_artist_top_chart(); //Artist Top Chart
				$data[] = $this->module_gallery_hot(); //Gallery Hot
				$data[] = $this->module_calendar(); //News Calendar
				$data[] = $this->module_activity(); //Activity
				$data[] = $this->module_keyword_tag(); //Keyword Tag
				$data[] = $this->module_gallery_new(); //Gallery New
				$data[] = $this->module_dream_ticket(); //Dream Ticket
			break;
			case 'backup':
				//$data[] = $this->module_login(); //Login
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->module_dream_ticket(); //Dream Ticket
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_gallery_new(); //Gallery New
				$data[] = $this->module_article(); //Article
				$data[] = $this->banner('C'); //Banner C
				//$data[] = $this->module_live_player(); //Live Player
				$data[] = $this->module_calendar(); //Calendar
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->module_activity(); //Activity
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
				$data[] = $this->module_keyword_tag(); //Keyword Tag
			break;								
			default: //default Mode
				$data[] = $this->banner('A'); //Banner A
				//$data[] = $this->banner('Music_Chart'); //Banner Music Chart
				$data[] = $this->module_music_top_chart(); //Music Top Chart
				$data[] = $this->banner('B'); //Banner B
				$data[] = $this->module_article(); //Article
				$data[] = $this->banner('C'); //Banner C
				$data[] = $this->module_gallery_new(); //Gallery New
				$data[] = $this->banner('D'); //Banner D
				$data[] = $this->module_calendar(); //Calendar
				$data[] = $this->banner('E'); //Banner E
				$data[] = $this->module_news_hot(); //News Hot
				$data[] = $this->module_activity(); //Activity
				$data[] = $this->module_facebook_plugins_likebox(); //Facebook Plugins Likebox
				$data[] = $this->module_keyword_tag(); //Keyword Tag
				$data[] = $this->banner('F'); //Banner F
				//$data[] = $this->module_live_player(); //Live Player
				//$data[] = $this->module_tweet_plugins(); //Facebook Plugin
		endswitch;
		return $data;
	} 
	  
   	/*Login*/
   	private function module_login()
   	{
		return $this->load->view("modules/login", $this->data, true);
   	}
	
	/*Music Top Chart*/
	private function module_music_top_chart()
	{
/*		$this->memcache->delete('dataMusicChartThai');
		$this->memcache->delete('dataMusicChartInter');
		$this->memcache->delete('dataMusicChartVideo');*/

		//Keep rank Top 10 each section by Redis
		$this->load->library('redis');
		if (intval(substr($this->redis->get('dataYou2PlayChartDate'),9,2)) != intval(date('d'))):
			$dataMusicChartThai = $this->db->select('t.song_id,SUM(t.song_click_views) as views')->
			join('song as j',"j.song_id=t.song_id AND j.media_type_id=1",'INNER')-> //media_type_id = 1 (Thai)
			order_by('views DESC')->
			group_by('t.song_id')->
			get_where('song_click_stat as t',"DATE(t.update_date) < DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)",10)->
			result();
			$dataMusicChartInter = $this->db->select('t.song_id,SUM(t.song_click_views) as views')->
			join('song as j',"j.song_id=t.song_id AND j.media_type_id=2",'INNER')-> //media_type_id = 2 (Inter)
			order_by('views DESC')->		
			group_by('t.song_id')->
			get_where('song_click_stat as t',"DATE(t.update_date) < DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)",10)->
			result();
			$dataMusicChartVideo = $this->db->select('j.video_id,SUM(video_click_views) as views')->
			join('video as j','j.video_id=t.video_id','INNER')->
			order_by('views DESC')->
			group_by('t.video_id')->
			get_where('video_click_stat as t',"DATE(t.update_date) < DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 2 DAY)",10)->
			result();
			$dataMusicChart = array();
			$dataMusicChart['date'] = date('d');
			foreach($dataMusicChartThai as $value):
				$dataMusicChart['thai'][] = $value->song_id; 
			endforeach;
			foreach($dataMusicChartInter as $value):
				$dataMusicChart['inter'][] = $value->song_id; 
			endforeach;
			foreach($dataMusicChartVideo as $value):
				$dataMusicChart['video'][] = $value->video_id; 
			endforeach;
			//Set Redis	
			$this->redis->set('dataYou2PlayChartDate', json_encode($dataMusicChart));
		endif;
		$dataMusicChart = json_decode($this->redis->get('dataYou2PlayChartDate'),true);
		
		/*Chart Thai*/
		if ( !$this->data['dataMusicChartThai'] = $this->memcache->get('dataMusicChartThai')):
			$this->data['dataMusicChartThai'] = $this->db->select('t.song_id,SUM(t.song_click_views) as views,k.chords_id')
			->join('song as j',"j.song_id=t.song_id AND j.media_type_id=1",'INNER') //media_type_id = 1 (Thai)
			->join('chords as k','k.song_id=t.song_id','LEFT')
			->order_by('views DESC')
			->group_by('t.song_id')
			->get_where('song_click_stat as t',"DATE(t.update_date) < CURDATE() AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND j.song_id != 11651",10)
			->result();
			foreach($this->data['dataMusicChartThai'] as $key => $value):
				$value->video = $this->db->select('j.video_id,j.video_name')
				->join('video_info as j','j.video_id=t.video_id','INNER')
				->get_where('video_song as t',array('t.song_id' => $value->song_id),1)->row();
				$value->artist = $this->db->select('j.artist_id,j.artist_name')->
				join('artist_info as j','j.artist_id=t.artist_id','INNER')->
				get_where('song_artist as t',array('t.song_id' => $value->song_id))->
				result();
				foreach($value->artist as $artist):
					$value->artist_id[] = $artist->artist_id;
					$value->artist_name[] = $artist->artist_name;
				endforeach;
				$dataAlbum = $this->db->select('t.song_name,k.album_file_name,k.album_file_ext')->
				join('song_album as j',"j.song_id=t.song_id AND j.is_default='1'",'LEFT')->
				join('album_info as k',"k.album_id=j.album_id",'LEFT')->
				get_where('song_info as t',array('t.song_id' => $value->song_id),1)->
				row();
				$value->song_name = $dataAlbum->song_name;
				$value->album_file_name = $dataAlbum->album_file_name;
				$value->album_file_ext = $dataAlbum->album_file_ext;
				//Find Rank From Redis
				$rank = array_search($value->song_id, $dataMusicChart['thai']);
				if(($rank === false) || ($rank > $key)): //up
					$value->rank = 'up';
				elseif($rank < $key): //Down
					$value->rank = 'down';
				else: //Stable
					$value->rank = 'stable';
				endif;
			endforeach;
			//Cache Set
			$this->memcache->set('dataMusicChartThai', $this->data['dataMusicChartThai'], $this->memcache_time);
		endif;
		/*Chart Inter*/
		if ( !$this->data['dataMusicChartInter'] = $this->memcache->get('dataMusicChartInter')):
			$this->data['dataMusicChartInter'] = $this->db->select('t.song_id,SUM(t.song_click_views) as views,k.chords_id')
			->join('song as j',"j.song_id=t.song_id AND j.media_type_id=2",'INNER') //media_type_id = 2 (Inter)
			->join('chords as k','k.song_id=t.song_id','LEFT')
			->order_by('views DESC')		
			->group_by('t.song_id')
			->get_where('song_click_stat as t',"DATE(t.update_date) < CURDATE() AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 1 DAY)",10)
			->result();
			foreach($this->data['dataMusicChartInter'] as $key => $value):
				$value->video = $this->db->select('j.video_id,j.video_name')
				->join('video_info as j','j.video_id=t.video_id','INNER')
				->get_where('video_song as t',array('t.song_id' => $value->song_id),1)->row();		
				$value->artist = $this->db->select('j.artist_id,j.artist_name')->
				join('artist_info as j','j.artist_id=t.artist_id','INNER')->
				get_where('song_artist as t',array('t.song_id' => $value->song_id))->
				result();
				foreach($value->artist as $artist):
					$value->artist_id[] = $artist->artist_id;
					$value->artist_name[] = $artist->artist_name;
				endforeach;
				$dataSongAlbum = $this->db->select('t.song_name,k.album_file_name,k.album_file_ext')->
				join('song_album as j',"j.song_id=t.song_id AND j.is_default='1'",'LEFT')->
				join('album_info as k',"k.album_id=j.album_id",'INNER')->
				get_where('song_info as t',array('t.song_id' => $value->song_id),1)->
				row();
				$value->song_name = $dataSongAlbum->song_name;
				$value->album_file_name = $dataSongAlbum->album_file_name;
				$value->album_file_ext = $dataSongAlbum->album_file_ext;
				//Find Rank From Redis
				$rank = array_search($value->song_id, $dataMusicChart['inter']);
				if(($rank === false) || ($rank > $key)): //up
					$value->rank = 'up';
				elseif($rank < $key): //Down
					$value->rank = 'down';
				else: //Stable
					$value->rank = 'stable';
				endif;		
			endforeach;
			//Cache Set
			$this->memcache->set('dataMusicChartInter', $this->data['dataMusicChartInter'], $this->memcache_time);
		endif;
		/*Chart Video*/
		if ( !$this->data['dataMusicChartVideo'] = $this->memcache->get('dataMusicChartVideo')):
			$this->data['dataMusicChartVideo'] = $this->db->select('j.video_id,j.video_type_id,j.is_relate_song,SUM(video_click_views) as views')->
			join('video as j','j.video_id=t.video_id','INNER')->
			order_by('views DESC')->
			group_by('t.video_id')->
			get_where('video_click_stat as t',"DATE(t.update_date) < CURDATE() AND DATE(t.update_date) >= DATE_SUB(CURDATE(),INTERVAL 1 DAY) AND j.video_id != 8488",10)->
			result();
			foreach($this->data['dataMusicChartVideo'] as $key => $value):
				if($value->is_relate_song == '1'):
					$value->artist = $this->db->select('j.artist_id,j.artist_name')
					->join('song_artist as k',"k.song_id=t.song_id AND is_default='1'",'INNER')
					->join('artist_info as j','j.artist_id=k.artist_id','INNER')
					->get_where('video_song as t',array('video_id' => $value->video_id))
					->result();				
				else:
					$value->artist = $this->db->select('j.artist_id,j.artist_name')
					->join('artist_info as j','j.artist_id=t.artist_id','INNER')
					->get_where('video_artist as t',array('video_id' => $value->video_id))
					->result();				
				endif;
				
				foreach($value->artist as $artist):
					$value->artist_id[] = $artist->artist_id;
					$value->artist_name[] = $artist->artist_name;
				endforeach;
				$dataVideo = $this->db->get_where('video_info',array('video_id' => $value->video_id),1)->row();
				$value->video_name = $dataVideo->video_name;
				$value->video_thumb_name = $dataVideo->video_thumb_name;
				$value->video_thumb_ext = $dataVideo->video_thumb_ext;
				//Find Rank From Redis
				$rank = array_search($value->video_id, $dataMusicChart['video']);
				if(($rank === false) || ($rank > $key)): //up
					$value->rank = 'up';
				elseif($rank < $key): //Down
					$value->rank = 'down';
				else: //Stable
					$value->rank = 'stable';
				endif;		
			endforeach;
			//Cache Set
			$this->memcache->set('dataMusicChartVideo', $this->data['dataMusicChartVideo'], $this->memcache_time);		
		endif;
		
		return $this->load->view("modules/music_top_chart", $this->data, true);
	}	
	
	/*Artist Top Chart*/
	private function module_artist_top_chart()
	{
/*		$this->memcache->delete('dataArtistChartThai');
		$this->memcache->delete('dataArtistChartInter');*/		
		if ( !$this->data['dataArtistChartThai'] = $this->memcache->get('dataArtistChartThai')):
			$this->data['dataArtistChartThai'] = $this->db->select('t.artist_id,k.artist_name,SUM(t.artist_click_views) as views')->
			join('artist as j',"j.artist_id=t.artist_id AND j.media_type_id=1",'INNER')-> //media_type_id = 1 (Thai)
			join('artist_info as k','k.artist_id=t.artist_id','INNER')->
			order_by('views DESC')->
			group_by('t.artist_id')->
			get_where('artist_click_stat as t',"t.update_date <= NOW() AND t.update_date >= DATE_SUB(NOW(),INTERVAL 7 DAY)",10)->
			result();
			foreach($this->data['dataArtistChartThai'] as $value):
				$dataArtistImage = $this->db
				->order_by("artist_image_order ASC,artist_image_id ASC")
				->get_where('artist_image',array('artist_id' => $value->artist_id),1)
				->row();
				$value->artist_file_name = @$dataArtistImage->artist_file_name;
				$value->artist_file_ext = @$dataArtistImage->artist_file_ext;
			endforeach;
			//Cache Set
			$this->memcache->set('dataArtistChartThai', $this->data['dataArtistChartThai'], $this->memcache_time);
		endif;
		/*Chart Inter*/
		if ( !$this->data['dataArtistChartInter'] = $this->memcache->get('dataArtistChartInter')):
			$this->data['dataArtistChartInter'] = $this->db->select('t.artist_id,k.artist_name,SUM(t.artist_click_views) as views')->
			join('artist as j',"j.artist_id=t.artist_id AND j.media_type_id=2",'INNER')-> //media_type_id = 2 (Inter)
			join('artist_info as k','k.artist_id=t.artist_id','INNER')->
			order_by('views DESC')->
			group_by('t.artist_id')->
			get_where('artist_click_stat as t',"t.update_date <= NOW() AND t.update_date >= DATE_SUB(NOW(),INTERVAL 7 DAY)",10)->
			result();
			foreach($this->data['dataArtistChartInter'] as $value):
				$dataArtistImage = $this->db
				->order_by("artist_image_order ASC,artist_image_id ASC")
				->get_where('artist_image',array('artist_id' => $value->artist_id),1)
				->row();
				$value->artist_file_name = @$dataArtistImage->artist_file_name;
				$value->artist_file_ext = @$dataArtistImage->artist_file_ext;
			endforeach;
			//Cache Set
			$this->memcache->set('dataArtistChartInter', $this->data['dataArtistChartInter'], $this->memcache_time);
		endif;		
		
		return $this->load->view("modules/artist_top_chart", $this->data, true);
	}
	
	/*Facebook Plugins Likebox*/	
	private function module_facebook_plugins_likebox()
	{
		return $this->load->view("modules/facebook_plugins_likebox", $this->data, true);
	}
	
	/*Facebook Plugins Comment (Public Only)*/	
	public function module_facebook_plugins_comment($url=NULL,$colorscheme=NULL)
	{
		$this->data['facebook_comment_url'] = @$url;
		$this->data['facebook_comment_colorscheme'] = @$colorscheme;
		return $this->load->view("modules/facebook_plugins_comment", $this->data, true);
	}
	
	/*Facebook Plugins Share (Public Only)*/	
	public function module_facebook_plugins_share($url=NULL,$colorscheme='light')
	{
		$this->data['facebook_share_url'] = @$url;
		$this->data['facebook_share_colorscheme'] = $colorscheme;
		return $this->load->view("modules/facebook_plugins_share", $this->data, true);
	}	
	
	/*Twitter Plugin*/	
	private function module_tweet_plugins()
	{
		return $this->load->view("modules/tweet_plugins", $this->data, true);
	}
	
	/*Dream Ticket*/
	private function module_dream_ticket()
	{
		if ( !$this->data['dataDreamTicket'] = $this->memcache->get('dataDreamTicket')):
			$this->data['dataDreamTicket'] = $this->db->select('t.song_id,j.song_name')
			->join('song_info as j','j.song_id=t.song_id','INNER')
			->join('song_artist as k','k.song_id=t.song_id','INNER')
			->join('artist as l','l.artist_id=k.artist_id','INNER')
			->order_by('t.song_id DESC')
			->get_where('song as t',array('l.is_show_dream_ticket' => '1','t.media_type_id' => 1),4)
			->result();
			foreach($this->data['dataDreamTicket'] as $value):
				$value->artist = $this->db->select('j.artist_id,j.artist_name')
				->join('artist_info as j','j.artist_id=t.artist_id','INNER')
				->get_where('song_artist as t',array('t.song_id' => $value->song_id))
				->result();
				$value->image = $this->db->select('j.album_file_name,j.album_file_ext')
				->join('album_info as j','j.album_id=t.album_id','INNER')
				->get_where('song_album as t',array('t.song_id' => $value->song_id,'is_default' => '1'),1)
				->row();	
			endforeach;		
			//Cache Set
			$this->memcache->set('dataDreamTicket', $this->data['dataDreamTicket'], $this->memcache_time);
		endif;
		
		return $this->load->view("modules/dream_ticket", $this->data, true);
	}
	
	/*Movie Timeline*/
	private function module_movie_timeline()
	{
		return $this->load->view("modules/movie_timeline", $this->data, true);
	}
	
	/*Movie News*/
	private function module_movie_news()
	{
		if ( !$this->data['dataModuleMovieNews'] = $this->memcache->get('dataModuleMovieNews')):
			$this->load->library('solr');
			$searchSolrNews = "id:news_* AND news_type_id_i:6";
			$this->data['dataModuleMovieNews'] = $this->solr->query($searchSolrNews)->limit(4)->order_by(array('id' => 'DESC'))->result();
			//Cache Set
			$this->memcache->set('dataModuleMovieNews', $this->data['dataModuleMovieNews'], $this->memcache_time);				
		endif;
		
		return $this->load->view("modules/movie_news", $this->data, true);		
	}
	
	/*Movie Song*/
	private function module_movie_song()
	{
		if ( !$this->data['dataModuleMovieSong'] = $this->memcache->get('dataModuleMovieSong')):										
			$movie_id = intval($this->uri->rsegment(3));
			$this->load->library('solr');
			$searchSolrSong = "";
			if($movie_id > 0):
				$is_exist = $this->db->from('movie')->where(array('movie_id' => $movie_id))->count_all_results();
				if(!empty($is_exist)):
					$dataMovie = $this->db->select('movie_tag')->get_where('movie_info',array('movie_id' => $movie_id),1)->row();
					if(!empty($dataMovie->movie_tag)):
						$movie_tag_arr = explode(',',$dataMovie->movie_tag);
						$searchSolrSong .= 'song_tag_s:'.trim($movie_tag_arr[0]).' OR ';
					endif;
				endif;	
			endif;
			if(!empty($searchSolrSong)):
				$searchSolrSong = 'id:song_* AND is_ost_song_i:1 AND ('.rtrim($searchSolrSong,' OR ').')';
			else:
				$searchSolrSong = 'id:song_* AND is_ost_song_i:1';
			endif;
			
			$this->data['dataModuleMovieSong'] = $this->solr->query($searchSolrSong)->limit(8)->order_by(array('last_modified' => 'DESC'))->result();
			if(empty($this->data['dataModuleMovieSong'])):
				$searchSolrSong = 'id:song_* AND is_ost_song_i:1';
				$this->data['dataModuleMovieSong'] = $this->solr->query($searchSolrSong)->limit(8)->order_by(array('last_modified' => 'DESC'))->result();			
			endif;
				
			foreach($this->data['dataModuleMovieSong'] as $value):
				$value->song_id = preg_replace('/^song_/','',$value->id);
				if(!empty($value->album_id_i_arr)):
					if(!is_array($value->album_id_i_arr)):
						$album_id = $value->album_id_i_arr;
					else:
						$album_id = $value->album_id_i_arr[0];
					endif;
					$searchSolrAlbum = 'id:album_'.$album_id;
					$value->image = $this->solr->query($searchSolrAlbum)->row();
				else:
					$value->image = '';
				endif;
			endforeach;
			//Cache Set
			$this->memcache->set('dataModuleMovieSong', $this->data['dataModuleMovieSong'], $this->memcache_time);				
		endif;
		
		return $this->load->view("modules/movie_song", $this->data, true);			
	}
	
	/*Calendar (Public Only)*/
	public function module_calendar()
	{
		if($this->input->post('ajax')) $this->ajax_module_calendar(TRUE);
		$this->memcache->delete('dataModuleCalendarEvent');
		if ( !$this->data['dataModuleCalendarEvent'] = $this->memcache->get('dataModuleCalendarEvent')):
			$this->data['dataModuleCalendarEvent'] = $this->ajax_module_calendar();
			//Cache Set
			$this->memcache->set('dataModuleCalendarEvent', $this->data['dataModuleCalendarEvent'], $this->memcache_time);			
		endif;
				
		return $this->load->view("modules/calendar", $this->data, true);	
	}
	
	private function ajax_module_calendar($ajax = FALSE)
	{
		$method = $this->input->post('method');
		$day = date('d');
		$month = $this->input->post('month');
		$year = $this->input->post('year');
		if(empty($month)) $month = date('n');
		if(empty($year)) $year = date('Y');
		if(!($month == date('n') && $year == date('Y'))) $day = '';
		$Ym = $year.sprintf('%02d',$month);
		$this->data['dataModuleCalendarElement'] = array(
			'd' => $day,
			'm' => $month,
			'y' => $year,
			'month_start' => date('w',mktime(1,1,1,$month,1,$year)),
			'month_end' => date('d',mktime(1,1,1,$month+1,0,$year)),
		);

		$dataModuleCalendarEvent = $this->db->select('t.calendar_id,t.calendar_activity_date_start,t.calendar_activity_date_end,j.calendar_subject')
		->join('calendar_info as j','j.calendar_id=t.calendar_id','INNER')
		//->group_by("DATE(t.calendar_activity_date_start)")
		//->order_by('t.calendar_id','DESC')
		->order_by('t.calendar_activity_date_start','ASC')
		->get_where('calendar as t',"t.is_publish = '1' AND (date_format(t.calendar_activity_date_start,'%Y%m') = '".$Ym."' OR date_format(t.calendar_activity_date_end,'%Y%m') = '".$Ym."')")
		->result();
		
		$this->data['dataModuleCalendarActivity'] = array();
		foreach($dataModuleCalendarEvent as $value):
			$start = date('Ym',strtotime($value->calendar_activity_date_start));
			$end = date('Ym',strtotime($value->calendar_activity_date_end));
			$start_date = intval(date('d',strtotime($value->calendar_activity_date_start)));
			$end_date = intval(date('d',strtotime($value->calendar_activity_date_end)));
			if($Ym == $start): //check this month
				if($Ym != $end):
					$end_date = $this->data['dataModuleCalendarElement']['month_end'];
				endif;
				for($i=$start_date;$i<=$end_date;$i++):
					$this->data['dataModuleCalendarActivity'][$i][] = array(
						'calendar_id' => $value->calendar_id,
						'calendar_subject' => $value->calendar_subject,
						//'news_brief' => $value->news_brief,
						'image' => @$this->db->order_by("calendar_image_order ASC,calendar_image_id ASC")->get_where('calendar_image',array('calendar_id' => $value->calendar_id),1)->row()
					);				
				endfor;
			else:
				if($Ym != $start):
					$start_date = 1;
				endif;				
				for($i=$start_date;$i<=$end_date;$i++):
					$this->data['dataModuleCalendarActivity'][$i][] = array(
						'calendar_id' => $value->calendar_id,
						'calendar_subject' => $value->calendar_subject,
						//'news_brief' => $value->news_brief,
						'image' => @$this->db->order_by("calendar_image_order ASC,calendar_image_id ASC")->get_where('calendar_image',array('calendar_id' => $value->calendar_id),1)->row()
					);				
				endfor;				
			endif;
		endforeach;
		
		if($ajax):
			echo $this->load->view("modules/ajax_calendar", $this->data, TRUE);
			exit;
		else:
			return $this->load->view("modules/ajax_calendar", $this->data, TRUE);		
		endif;		
	}
	
	private function module_keyword_tag()
	{
		if ( !$this->data['dataModuleKeyword'] = $this->memcache->get('dataModuleKeyword')):
			$limit = 20;
			$SQL = "SELECT * FROM (SELECT * FROM oni_keyword_tag WHERE keyword_tag_weight = '1' ORDER BY update_date DESC LIMIT 200) as keyword_tag ORDER BY RAND() LIMIT 20";
/*			$this->data['dataModuleKeyword'] = $this->db
			->order_by('is_new DESC,Keyword_tag_weight DESC,times DESC,RAND()')
			->get_where('keyword_tag',array('Keyword_tag_weight' => '1'),$limit)
			->result()*/;
			$this->data['dataModuleKeyword'] = $this->db->query($SQL)->result();
			//Cache Set
			$this->memcache->set('dataModuleKeyword', $this->data['dataModuleKeyword'], $this->memcache_time);			
		endif;
		
 		return $this->load->view("modules/keyword_tag", $this->data, true);
	}
	
	private function module_news_hot()
	{
		if ( !$this->data['dataModuleNewsHot'] = $this->memcache->get('dataModuleNewsHot')):
			$this->data['dataModuleNewsHot'] = $this->db
			->join('news_info as j','j.news_id=t.news_id','INNER')
			->order_by('t.views DESC,t.news_publish_date DESC')
			->get_where('news as t',"t.is_publish = '1' AND t.news_publish_date <= NOW() AND t.news_publish_date >= DATE_SUB(NOW(),INTERVAL 7 DAY)",6)
			->result();
			foreach($this->data['dataModuleNewsHot'] as $value):
				$value->image = $this->db->order_by("news_image_order ASC,news_image_id ASC")->get_where('news_image',array('news_id' => $value->news_id),1)->row();
			endforeach;
			//Cache Set
			$this->memcache->set('dataModuleNewsHot', $this->data['dataModuleNewsHot'], $this->memcache_time);				
		endif;
		
		return $this->load->view("modules/news_hot", $this->data, true);
	}
	
	private function module_gallery_hot()
	{
		if ( !$this->data['dataModuleGalleryHot'] = $this->memcache->get('dataModuleGalleryHot')):
			$this->data['dataModuleGalleryHot'] = $this->db
			->join('gallery_click_stat as j','j.gallery_id=t.gallery_id','INNER')
			->group_by('t.gallery_id')
			->order_by('gallery_click_views DESC')
			->get_where('gallery as t',"t.is_publish = '1' AND j.update_date > DATE_SUB(NOW(),INTERVAL 7 DAY)",5)
			->result();
			foreach($this->data['dataModuleGalleryHot'] as $value):
				$value->image = $this->db->order_by("gallery_image_order ASC,gallery_image_id ASC")->get_where('gallery_image',array('gallery_id' => $value->gallery_id),1)->row();
			endforeach;
			//Cache Set
			$this->memcache->set('dataModuleGalleryHot', $this->data['dataModuleGalleryHot'], $this->memcache_time);				
		endif;
		
		return $this->load->view("modules/gallery_hot", $this->data, true);
	}
	
	private function module_gallery_new()
	{
		if ( !$this->data['dataModuleGalleryNew'] = $this->memcache->get('dataModuleGalleryNew')):
			$this->data['dataModuleGalleryNew'] = $this->db
			->order_by('gallery_id DESC')
			->get_where('gallery as t',"t.is_publish = '1' AND (t.gallery_publish_date IS NULL OR t.gallery_publish_date < NOW())",3)
			->result();
			foreach($this->data['dataModuleGalleryNew'] as $value):
				$value->image = $this->db->order_by("gallery_image_order ASC,gallery_image_id ASC")->get_where('gallery_image',array('gallery_id' => $value->gallery_id),1)->row();
			endforeach;
			//Cache Set
			$this->memcache->set('dataModuleGalleryNew', $this->data['dataModuleGalleryNew'], $this->memcache_time);
		endif;
		
		return $this->load->view("modules/gallery_new", $this->data, true);
	}	
	
	private function module_activity()
	{
		//Load Scroll Bar
		$this->data['js'][] = 'jquery.perfect-scrollbar.min.js';
		$this->data['js'][] = 'jquery.perfect-scrollbar.with-mousewheel.min.js';
		$this->data['css'][] = 'jquery.perfect-scrollbar.min.css';
		if ( !$this->data['dataModuleActivity'] = $this->memcache->get('dataModuleActivity')):		
			$this->data['dataModuleActivity'] = $this->db->select('t.activity_id,j.activity_subject,t.is_show_sidebar')
			->join('activity_info as j','j.activity_id=t.activity_id','INNER')
			->order_by('t.activity_id DESC')
			//->get_where('activity as t',"t.is_publish = '1' AND (t.activity_date_end > NOW() OR t.activity_auth_date > NOW()) AND t.is_show_sidebar = '1'")
			->get_where('activity as t',"t.is_publish = '1' AND t.is_show_sidebar = '1'")
			->result();
			foreach($this->data['dataModuleActivity'] as $value):
				$value->image = $this->db->order_by("activity_image_order ASC,activity_image_id ASC")->get_where('activity_image',array('activity_id' => $value->activity_id),1)->row();
			endforeach;	
			//Cache Set
			$this->memcache->set('dataModuleActivity', $this->data['dataModuleActivity'], $this->memcache_time);			
		endif;	
				
		return $this->load->view("modules/activity", $this->data, true);
	}
	
	private function module_article()
	{
		if ( !$this->data['dataModuleArticle'] = $this->memcache->get('dataModuleArticle')):		
			$this->data['dataModuleArticle'] = $this->db->select('t.news_id,j.news_subject')->
			join('news_info as j','j.news_id=t.news_id','INNER')->
			order_by('news_id','DESC')->
			get_where('news as t',array('t.news_type_id' => 7,'t.is_publish' => '1'),2)->result();
			foreach($this->data['dataModuleArticle'] as $value):
				$value->image = $this->db->order_by("news_image_order ASC,news_image_id ASC")->get_where('news_image',array('news_id' => $value->news_id),1)->row();
			endforeach;
			
			//Cache Set
			$this->memcache->set('dataModuleArticle', $this->data['dataModuleArticle'], $this->memcache_time);			
		endif;	
				
		return $this->load->view("modules/article", $this->data, true);		
	}
	
	private function module_live_player()
	{
		//Load Media Player
		if($this->agent->is_mobile()):
			//Do Nothing
		else:
			$this->data['js'][] = "media/jwplayerx.js";
		endif;
			
		return $this->load->view("modules/live_player", $this->data, true);
	}
	
	/*Video Recommend*/
	private function module_video_recommend()
	{
		//Load Media Player
		if($this->agent->is_mobile()):
			//Do Nothing
		else:
			$this->data['js'][] = "media/jwplayerx.js";
		endif;
		
		if ( !$this->data['dataModuleVideoRecommend'] = $this->memcache->get('dataModuleVideoRecommend')):
			$dataJson = json_decode($this->db->select('json')
			->get_where('module_page',array('page' => 'video_recommend'),1)
			->row()->json);
			$video_arr = array();
			foreach($dataJson as $value):
				shuffle($value);
				$video_arr[] = current($value);			
			endforeach;
			$this->db->_protect_identifiers = FALSE; // stop CI adding backticks
			$this->data['dataModuleVideoRecommend'] = $this->db->select('t.video_id,t.is_relate_song,j.video_name,t.views,j.video_thumb_name,j.video_thumb_ext')->
			join('video_info as j',"j.video_id=t.video_id",'INNER')->
			order_by("FIELD(t.video_id,".implode(',',$video_arr).")", "DESC")->
			get_where('video as t',"t.video_id IN (".implode(',',$video_arr).")",5)->
			result();
			$this->db->_protect_identifiers = TRUE; // start CI adding backticks
			foreach($this->data['dataModuleVideoRecommend'] as $value):
				if($value->is_relate_song == '1'):
					$value->artist = $this->db->select('j.artist_id,j.artist_name')
					->join('song_artist as k',"k.song_id=t.song_id AND is_default='1'",'INNER')
					->join('artist_info as j','j.artist_id=k.artist_id','INNER')
					->get_where('video_song as t',array('video_id' => $value->video_id))
					->result();				
				else:
					$value->artist = $this->db->select('j.artist_id,j.artist_name')
					->join('artist_info as j','j.artist_id=t.artist_id','INNER')
					->get_where('video_artist as t',array('video_id' => $value->video_id,'t.is_default' => '1'))
					->result();				
				endif;					
			endforeach;			
			//Cache Set
			$this->memcache->set('dataModuleVideoRecommend', $this->data['dataModuleVideoRecommend'], $this->memcache_time);				
		endif;	

		return $this->load->view("modules/video_recommend", $this->data, true);		
	}
	/**************************End Module Management**************************/
	
	/**************************Page Missing**************************/
	public function page_missing()
	{
		//fire your php http 404 not found header

		//$var h;ps a string that can be passed the to view so that you can
		//display some custom text on the 404 page to make it a bit more
		//user friendly. I like to put a little note (deleted, not found, etc) and
		// a link to the most relevant page
		$this->output->set_status_header('404');
		$this->data['content'] = "errors/page_missing";
		if($this->router->class=="news" || $this->router->class=="calendar" || $this->router->class=="gallery"):
			$templates = "templates_news";
		else:
			$templates = "templates";
		endif;
		echo $this->load->view("templates/".$this->folder_templates.$templates, $this->data, TRUE);
		exit;	
	}
	/**************************End Page Missing**************************/	
}
// END MY_Controller class

/**
 * CodeIgniter MY_Administrator Class
 *
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Libraries
 * @author		ONIPHP CO.,LTD
 * @link		http://www.oniphp.com
 */
class MY_Administrator extends CI_Controller {
   	public function __construct()
   	{
        parent::__construct();
		//Load model
		$this->load->model('administrator_model');
		//Load Language
		$this->lang->load('backend','english');		
		//Check Login
		$this->administrator_model->login();
		//Load Library
		$this->load->helper('text');
		//Set Title
		$this->data['Title'] = "Content Management System";
		//Set Meta
		$this->data['mTitle'] = "Content Management System";
		$this->data['mDesc'] = "Content Management System";
		$this->data['mKey'] = "Content Management System";
		//Set Templates
		$this->folder_templates = "backoffice/";
        //Set Script Default	
        $this->data['js'] = array('jquery-1.8.3.min.js','hoverIntent.js','common.js','swfobject.js','jquery.validate.min.js','backScript.js');
        //Set Style Default	
        $this->data['css'] = array('dashboard.css','global.css','wp-admin.css','colors-fresh.css','ie.css');
        //Set Script External Default	
        $this->data['external_js']  = '';
        //Set style External Default	
        $this->data['external_css'] = "";
		//Set Temp Folder
		$this->temp_folder = $this->config->item('path_asset_url').'temp/';		
		//Set Upload Folder
		$this->upload_folder = $this->config->item('path_asset_url').'assets/uploads/';
		//Load Library
		$this->load->library('pagination');	
		
		//External Connection
		exec("ping -c 1 ".$this->input->server('HTTP_HOST')." && exit", $output);
  		if(!preg_match('/smtp.you2play.com/',$output[1])):
			$this->data['external_connection'] = true;
			$this->data['external_connection_timeout'] = 60*60*100; //1 hours
  		endif;			
   	}
	
	/**************************Login System**************************/
	/*Login*/
	public function login()
	{
		//If Login Remember
		if(@$this->input->cookie('rememberme')):
			redirect(base_url());
		endif;
		
		//Load Library
		$this->load->library('form_validation');
		$this->form_validation->set_rules('user_login', 'Username', 'trim|required');
		$this->form_validation->set_rules('user_pass', 'Password', 'trim|required');			
		if ($this->form_validation->run() == FALSE):
			if(isset($_POST) && !empty($_POST)):
				$this->data['error'] = 1;
			else:
				$this->data['error'] = 0;
			endif;
		elseif($this->administrator_model->login() == FALSE):
			//Keep Log Error
			$path_log_error = $this->config->item('path_log_error');
			$file = $path_log_error.date('Y-m-d').".txt";
			$ip = $this->input->ip_address();
			$username = $this->input->post('user_login');
			$log = "User: ".$username." IP: ".$ip."\r\n";
			file_put_contents($file, $log, FILE_APPEND);
			$this->data['error'] = 2;
		else:
			redirect(base_url());
		endif;
		
		//Load Javascript
		if(!empty($this->data['error'])) $this->data['js']   = array('jquery-1.8.2.min.js','shake.js');
		//Load Style Sheet
		$this->data['css']   = array('login.css','colors-fresh.css');
		
		$this->load->view("templates/".$this->folder_templates."templates_login", $this->data);		
	}
	
	/*Logout*/
	public function logout()
	{
		$this->administrator_model->logout();
		redirect(base_url());			
	}
	/**************************End Login System**************************/	
}
// END MY_Administrator class

/* End of file Fb.php */
/* Location: ./application/libraries/Fb.php */
